<template>
  <div class="content">
    <!-- <div class="searchBox">
      <div>
        <div class="searchBox-title">
          <span>食材类型选择</span>
          <Select v-model="typeName" style="width: 200px" @on-change="
            purchasingfoodListApi();
          selectaiconfigfoodApi();
          " size="small" class="ml_10">
            <Option v-for="(item, index) in typeList" :key="index" :value="item.name">{{
              item.name
            }}</Option>
          </Select>
        </div>
      </div>
    </div> -->
    <cus-search style="min-width: 1000px;padding-bottom: 0px;" class="mb_20">
      <cus-search-item>
        <Form ref="formValidate" :label-width="110">
          <FormItem class="mr_48 mb_20" label="食材类型选择">
            <Select v-model="typeName" style="width: 200px" @on-change="
              purchasingfoodListApi();
            selectaiconfigfoodApi();
            " size="small" class="ml_10">
              <Option v-for="(item, index) in typeList" :key="index" :value="item.name">{{
                item.name
              }}</Option>
            </Select>
          </FormItem>
        </Form>
      </cus-search-item>
    </cus-search>
    <Row :gutter="16" style="height: 100%">
      <Col span="24" style="position: relative">
      <Spin size="large" fix v-if="loading"> </Spin>
      <div class="content-item" style="padding: 20px; height: calc(100vh - 200px)">
        <div class="btnBox">
          <div class="btnBox-left">
            <div style="display: flex">
              <Input v-trim v-model="leftFoodName" placeholder="输入食材名称搜索" clearable class="mr_10" />
              <cusButton type="primary" @onClick="purchasingfoodListApi()">查询</cusButton>
            </div>
            <div style="font-size: 14px; margin-left: 10px">
              当前食材：{{ leftDataLength }} 个
            </div>
          </div>
          <!-- <div class="btnBox-right">
                <Checkbox
                  v-model="selectAll"
                  @on-change="selectAllLeftChange()"
                  :disabled="rightDataList.length == leftDataLength"
                >
                  全选添加
                </Checkbox>
              </div> -->
        </div>
        <div class="dishesBox" style="height: calc(100vh - 330px); overflow: hidden; overflow-y: auto">
          <!-- <CheckboxGroup v-model="selectDishes" @on-change="leftChange">
                <Checkbox
                  :label="item.materialId"
                  v-for="item in data"
                  :key="item.materialId"
                  style="margin-right: 15px; margin-bottom: 15px"
                  :disabled="item.configFoodSelected == 1"
                >
                  <span @contextmenu.prevent="connectDishesBtn(item)"
                    >{{ item.materialName
                    }}{{ item.configFoodSelected == 1 ? '（已选择）' : '' }}</span
                  >
                </Checkbox>
              </CheckboxGroup> -->
          <Tag type="border" color="primary" v-for="item in data" :key="item.materialId"
            style="margin-right: 10px; margin-bottom: 10px; cursor: pointer">
            <div>
              <span @contextmenu.prevent="connectDishesBtn(item)">{{
                item.materialName
              }}</span>
            </div>
          </Tag>
        </div>
        <div style="padding-top: 10px">*鼠标右键食材，可以查看食材关联的相关菜肴</div>
      </div>
      </Col>
    </Row>

    <!-- 关联菜肴列表 -->
    <connectDishes ref="connectDishes"></connectDishes>
  </div>
</template>

<script>
import {
  localfoodtypeList,
  purchasingfoodList,
  selectaiconfigfood,
  saveaiconfigfood,
  deleteAiConfigFood,
} from "@/api/business/dishesModule";
import connectDishes from "./components/connectDishes";
export default {
  components: { connectDishes },
  data() {
    return {
      loading: false,
      loadingRight: false,
      typeName: "全部",
      typeList: [],
      leftFoodName: "", // 左侧食材名
      rightFoodName: "", // 右侧食材名
      data: [],
      rightdata: [],
      selectDishes: [],
      selectDishesRight: [],
      selectAll: false, // 是否全选左侧
      selectAllRight: false, // 是否全选左侧,
      leftHandlerId: null,
      rightHanderId: null,
      leftDataLength: 0,
      leftDataList: [],
      rightDataLength: 0,
      rightDataList: [],
    };
  },
  mounted() {
    this.localfoodtypeListApi();
    this.purchasingfoodListApi();
    this.selectaiconfigfoodApi();
  },
  destroyed() {
    if (this.leftHandlerId) {
      cancelAnimationFrame(this.leftHandlerId);
    }
    if (this.rightHanderId) {
      cancelAnimationFrame(this.rightHanderId);
    }
  },
  methods: {
    // 获取食材分类列表
    localfoodtypeListApi() {
      return new Promise((resolve) => {
        localfoodtypeList({}).then((res) => {
          if (res.retCode == 2000) {
            this.typeList = res.data;
            this.typeList.unshift({ name: "全部", id: "" });
            resolve();
          }
        });
      });
    },
    // 可选食材列表 (左边) 列表
    purchasingfoodListApi() {
      this.loading = true;
      this.data = [];
      if (this.leftHandlerId) {
        cancelAnimationFrame(this.leftHandlerId);
      }
      return new Promise((resolve) => {
        purchasingfoodList({
          foodClassName: this.typeName == "全部" ? "" : this.typeName,
          foodName: this.leftFoodName,
        }).then((res) => {
          this.loading = false;
          if (res.retCode == 2000) {
            this.leftDataList = res.data.records || res.data;
            this.leftDataLength = res.data.records.length;
            this.renderOptimization(
              res.data.records || res.data,
              "data",
              "leftHandlerId"
            );
            // this.data = res.data.records || res.data;
            resolve();
          }
        });
      });
    },
    averageFn(arrList) {
      let i = 0;
      let result = [];
      while (i < arrList.length) {
        result.push(arrList.slice(i, i + 10));
        i = i + 10;
      }
      return result;
    },
    renderOptimization(dataList, data, handlerId) {
      let twoArrayList = this.averageFn(dataList);
      console.log(twoArrayList);
      const renderFuc = (currentIndex) => {
        if (currentIndex > twoArrayList.length - 1) {
          cancelAnimationFrame(this.handlerId);
          return;
        }
        console.log(this[data]);
        this[handlerId] = requestAnimationFrame(() => {
          this[data] = [...this[data], ...twoArrayList[currentIndex]];
          currentIndex = currentIndex + 1;
          renderFuc(currentIndex);
        });
      };
      renderFuc(0);
    },
    // 可选食材列表 (右边) 列表
    selectaiconfigfoodApi() {
      this.loadingRight = true;
      this.rightdata = [];
      if (this.rightHanderId) {
        cancelAnimationFrame(this.rightHanderId);
      }
      return new Promise((resolve) => {
        selectaiconfigfood({
          foodClassName: this.typeName == "全部" ? "" : this.typeName,
          foodName: this.rightFoodName,
        }).then((res) => {
          this.loadingRight = false;
          if (res.retCode == 2000) {
            this.rightDataList = res.data.records || res.data;
            this.rightDataLength = res.data.records.length;
            this.renderOptimization(
              res.data.records || res.data,
              "rightdata",
              "rightHanderId"
            );
            resolve();
          }
        });
      });
    },
    // 保存已选食材
    saveaiconfigfoodApi(arr) {
      this.loading = true;
      return new Promise((resolve) => {
        saveaiconfigfood(arr).then((res) => {
          this.loading = false;
          if (res.retCode == 2000) {
            this.$Message.success("食材添加成功.");
            resolve();
          }
          this.selectDishes = [];
          this.purchasingfoodListApi();
          this.selectaiconfigfoodApi();
        });
      });
    },
    // 删除食材
    deleteAiConfigFoodApi(arr) {
      this.loading = true;
      return new Promise((resolve) => {
        deleteAiConfigFood(arr).then((res) => {
          this.loading = false;
          if (res.retCode == 2000) {
            this.$Message.success("食材移除成功.");
            resolve();
          }
          this.selectDishesRight = [];
          this.purchasingfoodListApi();
          this.selectaiconfigfoodApi();
        });
      });
    },
    // 左侧选项切换
    leftChange() {
      let arr = [];
      if (this.leftHandlerId) {
        cancelAnimationFrame(this.leftHandlerId);
      }
      this.selectDishes.forEach((item) => {
        this.data.map((aItem) => {
          if (aItem.materialId == item) {
            arr.push(aItem);
            return;
          }
        });
      });
      this.saveaiconfigfoodApi(arr);
    },
    // 右侧选项变化
    rightChange() {
      let arr = [];
      if (this.rightHandlerId) {
        cancelAnimationFrame(this.rightHandlerId);
      }
      this.selectDishesRight.forEach((item) => {
        this.rightdata.map((aItem) => {
          if (aItem.materialId == item) {
            arr.push(aItem);
            return;
          }
        });
      });
      this.deleteAiConfigFoodApi(arr);
    },
    // 右侧全选
    selectAllRightChange() {
      if (this.rightHandlerId) {
        cancelAnimationFrame(this.rightHandlerId);
      }
      if (this.selectAllRight) {
        this.$Modal.confirm({
          title: "删除警告",
          content: "是否确认删除所有已选食材？",
          onOk: () => {
            this.selectAllRight = false;
            this.selectDishesRight = this.rightDataList.map((item) => item.materialId);
            this.deleteAiConfigFoodApi(this.rightDataList);
          },
          onCancel: () => {
            this.selectAllRight = false;
          },
        });
      }
    },
    // 左侧全选
    selectAllLeftChange() {
      if (this.leftHandlerId) {
        cancelAnimationFrame(this.handlerId);
      }
      if (this.selectAll) {
        this.$Modal.confirm({
          title: "添加确认",
          content: "是否确认添加该品类下所有未添加的食材？",
          onOk: () => {
            this.selectAll = false;
            this.selectDishes = this.leftDataList.map(
              (item) => item.configFoodSelected != 1 && item.materialId
            );
            let arr = this.leftDataList.filter((item) => item.configFoodSelected != 1);
            this.saveaiconfigfoodApi(arr);
          },
          onCancel: () => {
            this.selectAll = false;
          },
        });
      }
    },
    connectDishesBtn(item) {
      this.$refs["connectDishes"].form.materialId = item.materialId;
      this.$refs["connectDishes"].form.name = item.materialName;
      this.$refs["connectDishes"].show();
    },
  },
};
</script>
<style scoped>
::deep .ivu-input-icon {
  height: 40px !important;
  line-height: 40px !important;
}

#html .ivu-radio-group {
  display: flex;
  flex-wrap: wrap !important;
  justify-content: center;
}

.ivu-radio-group-vertical .ivu-radio-wrapper {
  display: block;
  height: auto !important;
  line-height: 1 !important;
  margin-right: 0 !important;
}
</style>
<style lang="less" scoped>
/*里面的代码可以根据自己需求去进行更改*/
/* 设置滚动条的样式 */
::-webkit-scrollbar {
  width: 4px;
}

/* 滚动槽 */
::-webkit-scrollbar-track {
  -webkit-box-shadow: inset006pxrgba(0, 0, 0, 0.3);
  border-radius: 10px;
}

/* 滚动条滑块 */
::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: rgba(0, 0, 0, 0.1);
  -webkit-box-shadow: inset006pxrgba(0, 0, 0, 0.5);
}

::-webkit-scrollbar-thumb:window-inactive {
  background: rgba(255, 255, 255, 0.4);
}

.content {
  height: calc(100% - 138px);

  // position: relative;
  // background: green;
  &-item {
    background: #ffffff;
    border-radius: 6px;
    box-shadow: 0px 4px 8px 0px rgba(108, 137, 165, 0.18);
    // box-shadow: 1px 1px 2px 0px rgba(153, 182, 199, 0.2);
  }
}

.radioBox {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  overflow: hidden;
  overflow-y: auto;
  padding-bottom: 10px;
}

.btnBox {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;

  &-left {
    display: flex;
    align-items: center;
  }

  &-right {
    display: flex;
    align-items: center;
  }
}

.dishesBox {
  // height: calc(100% - 70px)!important;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  padding: 10px;
  overflow: hidden;
  overflow-y: auto;
}

.searchBox {
  height: 80px;
  background: #ffffff;
  border-radius: 4px;
  box-shadow: 1px 1px 2px 0px rgba(153, 182, 199, 0.2);
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  padding: 0 20px;

  &-title {
    font-size: 14px;
    font-family: PingFang SC-Medium, PingFang SC;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.75);
  }
}
</style>
